package com.hp.bon.sgw.wh.channel.handler;

import com.hp.bon.omc.util.StringUtil;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.bean.tmall.FixedBroadOrderBean;
import com.hp.bon.sgw.wh.channel.TMallChannel;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.ResultCodeUtil;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_Grouped;
import com.hp.ocs.diameter.message.AVP_UTF8String;
import com.hp.ocs.diameter.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: TMallOrderQueryHandle
 * @Description: TODO
 * @author: kaiyang
 * @date:2015年5月4日 下午2:44:53
 * @update By C.J
 * @date 2017年12月4日 下午4:02:39
 */
public class FixedBroadOrderQueryHandle implements IAsynCallHandler {
    private static final Logger _log = LoggerFactory.getLogger(TaobaoFeeHandle.class);
    private UserResourceConfigService userResourceConfigService;

    @Override
    public void onCallResult(CallParam callParam) {
        XmlMessage ack = null;
        Object response = null;
        if (callParam.getResponse() != null) {
            response = callParam.getResponse();
        } else if (callParam.getRecvResponse() != null) {
            response = callParam.getRecvResponse();
        }
        if (response == null) {
            _log.info("response is null");
            ack = SoapChannel.createERRAnwser(
                    callParam.getSessionId(),
                    callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode(), callParam.getResultMsg());
        } else {
            if (response instanceof Message) {
                _log.info("response type  is Message");
                ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
            } else if (response instanceof XmlMessage) {
                _log.info("response type  is XmlMessage");
                ack = (XmlMessage) response;
            } else {
                _log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
            }
        }
        try {
            String respXML = convertResponseString((Message) response, callParam.getServiceResultCode());
            byte[] resp = respXML.getBytes("UTF-8");
            ack.setLength(resp.length);
            ack.setMsgTime(System.currentTimeMillis());
            printStream.write(resp);
            printStream.close();
            callParam.setResponse(ack);
            if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
                MessageDetail detail = new MessageDetail();
                detail.setBusinessCallId(callParam.getBussinessCallId());
                detail.setSessionId(callParam.getSessionId());
                detail.setServiceContextId(callParam.getServiceContextId());
                detail.setMessageType(MessageType.WSA);
                detail.setDetails(ack.getDATA());
                detail.setMsgTime(new Date(ack.getMsgTime()));
                detail.setOpType("send");
                detail.setHostId(callParam.getUserName());
                MessageDetailCacheManager.getInstance().add(detail);
            }
            TaskManager.taskProcess(callParam);
            _log.info("http response(taobao) " + respXML);
        } catch (Exception e) {
            _log.error("",e);
        }
    }

    private String convertResponseString(Message answer, int serviceResultCode) {
        _log.info("FixedBroadOrderQueryHandle convertResponseString:serviceResultCode={}", serviceResultCode);
        String response = "";
        Map<String, String> data = new HashMap<String, String>();
        data.put("tbOrderNo", fixedBroadOrderBean.getTbOrderNo());
        data.put("bizType", fixedBroadOrderBean.getBizType());
        data.put("coopOrderNo", "");
        data.put("errDesc", "");
        String Para_Field_Result = "";
        userResourceConfigService = SpringContext.getApplicationContext().getBean(UserResourceConfigService.class);
        String rechargeState = "";
        String billSerialNbr = "";
        String taobao_defaultResult = userResourceConfigService.getValue("taobao_defaultResult");

        try {
            //service_infomation
            AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION, Constants.DIAMETER_VENDOR_3GPP);
            AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
            //Bill_Serial_Nbr
            AVP avpBillSerialNbr = avpServiceInfomation.find(80133, Constants.DIAMETER_VENDOR_CT);
            if (avpBillSerialNbr != null)
                billSerialNbr = new AVP_UTF8String(avpBillSerialNbr).queryValue();
            //rechage_state 0 没有记录, 当为此值时,下面几项都填 0,1 充值成功, 2 已经返销
            AVP avpRechageState = avpServiceInfomation.find(82013, Constants.DIAMETER_VENDOR_CT);
            if (avpRechageState != null)
                rechargeState = new AVP_UTF8String(avpRechageState).queryValue();
            AVP Para_Field_Result_VP = avpServiceInfomation.find(80407, Constants.DIAMETER_VENDOR_CT);
            if (Para_Field_Result_VP != null)
                Para_Field_Result = new AVP_UTF8String(Para_Field_Result_VP).queryValue();
            if (0 == serviceResultCode) {
                if (rechargeState.equals("0") || rechargeState.equals("2")) {
                    // 0 和 2
                    data.put("coopOrderStatus", TMallChannel.STATUS_FAIL);
                } else {
                    data.put("coopOrderStatus", TMallChannel.STATUS_SUCCESS);
                }
            }else{
                //失败
                data.put("coopOrderStatus", TMallChannel.REQUEST_FAIL);
            }
        } catch (Exception e) {
            _log.error("",e);
            data.put("coopOrderStatus", TMallChannel.STATUS_UNDERWAY);
        }
        data.put("coopOrderNo", fixedBroadOrderBean.getTbOrderNo());
        String newCode = ResultCodeUtil.updateResultCode(serviceResultCode, userResourceConfigService.getValue("taobao_resultCode"), taobao_defaultResult);
        data.put("errCode", newCode);
        data.put("errDesc", Para_Field_Result);

        String coopOrderStatus = data.get("coopOrderStatus");
        if(coopOrderStatus.equals(TMallChannel.STATUS_SUCCESS) || coopOrderStatus.equals(TMallChannel.STATUS_UNDERWAY)){
            data.put("errCode", "");
            data.put("errDesc", "");
            data.put("coopOrderNo", billSerialNbr);
        }else if(StringUtil.isBlank(Para_Field_Result)){
            data.put("errDesc", "其他异常");
        }
        if (0 == serviceResultCode && (rechargeState.equals("0") || rechargeState.equals("2"))) {
            data.put("errCode", TMallChannel.ORDER_NOT_EXIST);
            data.put("errDesc", TMallChannel.ORDER_NOT_EXIST);
        }
        response = tmallResponseService.getResponse1(data);
        return response;
    }

    private PrintStream printStream;
    private FixedBroadOrderBean fixedBroadOrderBean;
    private TMallResponseService tmallResponseService;
    @SuppressWarnings("unused")
    private ThreadPoolTaskExecutor asynExecutor;
    @SuppressWarnings("unused")
    private String tmallRetUrl;
    @SuppressWarnings("unused")
    private String pubKeyValue;

    public FixedBroadOrderQueryHandle(PrintStream printStream, FixedBroadOrderBean fixedBroadOrderBean, TMallResponseService tmallResponseService, ThreadPoolTaskExecutor asynExecutor, String tmallRetUrl, String pubKeyValue) {
        this.printStream = printStream;
        this.fixedBroadOrderBean = fixedBroadOrderBean;
        this.tmallResponseService = tmallResponseService;
        this.asynExecutor = asynExecutor;
        this.tmallRetUrl = tmallRetUrl;
        this.pubKeyValue = pubKeyValue;
    }

    @Override
    public int getProtocolType() {
        return 0;
    }
}
